package bhbt.controller;


import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import bhbt.controller.core.BaseController;
import bhbt.model.Member;
import bhbt.model.log.LogOperMember;
import bhbt.service.MemberService;
import bhbt.service.log.LogOperMemberService;
import bhbt.utils.CryptUtil;
import bhbt.utils.MapUtil;
import bhbt.utils.SysConst;






/**
 * 登录
 */
@Controller
public class LoginController extends BaseController {

	@Resource
	private MemberService memberService;
	@Resource
	private LogOperMemberService logOperMemberService;

	

	@RequestMapping("loginShow.shtml")
	public String loginShow(ModelMap model, HttpSession session, HttpServletRequest request) throws Exception{
		 
		return "login";
	}
	
	@RequestMapping("login.shtml")
	public String submit(ModelMap model, HttpSession session, HttpServletRequest request) throws Exception{
		Map formMap = getParameterMap(request);
		
//		String validateSession=(String)session.getAttribute("validate");
//		String validate =  MapUtil.getString(formMap, "validate");
//		 
//		if (validate==null) {
//			setMessage(model,"请输入验证码。");
//			return "loginMember";
//		}else{
//			if(!validate.equals(validateSession)){
//				setMessage(model,"验证码不正确。");
//				return "loginMember";
//			}
//		}
		
		
		String onePassword =  MapUtil.getString(formMap, "onePassword"); 
		String loginName =  MapUtil.getString(formMap, "loginName");
		Member member = verifyUser(loginName);
		
		if(null != member){
			//密码加密
			onePassword = CryptUtil.getInstance().encrypt2String(onePassword,CryptUtil.keyStr);
			if(onePassword.equals(member.getOnePassword())){
				
				if("F".equals(member.getAccountUse())||"F".equals(member.getAccountActive())){
					setMessage(model,"该用户已被禁用或者未激活!");
					return "login";
				}
				else{
					
					//一级密码（登录密码）连续输错三次，被锁定两个小时
					if(member.getErrorNum()>=3){
						
						Integer mm=(int)((new Date().getTime()-member.getErrorDate().getTime())/(1000*60));	//间隔分钟数
						if(mm<=120){
							setMessage(model,"密码连续错误三次以上，帐号被锁定，请等待"+(120-mm)+"分钟后再次登录！");
							return "login";
							
						}else{
							//更新信息
							Map map2 = new HashMap();
							 
				        	map2.put("id",member.getId());
				        	map2.put("errorNum", 0);
				        	map2.put("lastTime",member.getLoginTime());
				        	map2.put("loginTime",new Date());
				        	
				        	if(member.getLoginNum()==null){
								map2.put("loginNum",1);
							}else{
								map2.put("diyUpdate","loginNum=loginNum+"+1);
							}
				        	memberService.update(map2);
							
				        	member = memberService.getByKey(member.getId());
				        	session.setAttribute(SysConst.MEMBER, member);
							
				        	
				        	//登陆日志
				        	
				        	LogOperMember log=new LogOperMember();
							log.setType(10);				//操作类别(10系统登录)
							log.setMemberId(member.getId());
							log.setTitle("系统登录");
							
							String operIp=request.getRemoteHost();
							log.setOperIp(operIp);
							
							log.setCommitDate(new Date());
							log.setContext("登录成功");
							logOperMemberService.saveOrUpdate(log); 
							
							return "redirect:member/userManage.shtml";
						} 
					}else{
						//更新信息
						Map map2 = new HashMap();
						 
			        	map2.put("id",member.getId());
			        	map2.put("errorNum", 0);
			        	map2.put("lastTime",member.getLoginTime());
			        	map2.put("loginTime",new Date());
			        	
			        	if(member.getLoginNum()==null){
							map2.put("loginNum",1);
						}else{
							map2.put("diyUpdate","loginNum=loginNum+"+1);
						}
			        	memberService.update(map2);
						
			        	member = memberService.getByKey(member.getId());
			        	session.setAttribute(SysConst.MEMBER, member);
						
			        	
			        	//登陆日志
			        	
			        	LogOperMember log=new LogOperMember();
						log.setType(10);				//操作类别(10系统登录)
						log.setMemberId(member.getId());
						log.setTitle("系统登录");
						
						String operIp=request.getRemoteHost();
						log.setOperIp(operIp);
						
						log.setCommitDate(new Date());
						log.setContext("登录成功");
						logOperMemberService.saveOrUpdate(log); 
						
						return "redirect:member/userManage.shtml";
					}
					
					
					
				} 
				
			}else{
				
				
				//一级密码（登录密码）连续输错三次，被锁定两个小时
				if(member.getErrorNum()>=3){
					
					Integer mm=(int)((new Date().getTime()-member.getErrorDate().getTime())/(1000*60));	//间隔分钟数
					if(mm<=120){
						setMessage(model,"密码连续错误三次以上，帐号被锁定，请等待"+(120-mm)+"分钟后再次登录！");
						return "login";
						
					} 
						
				}else{
					//密码错误，添加错误信息
					//更新信息 
					Map map2 = new HashMap();
		        	map2.put("id",member.getId());
		        	map2.put("errorDate",new Date());
		        	map2.put("diyUpdate","errorNum=errorNum+"+1);
		        	memberService.update(map2);
		        	
		        	//登陆记录
		        	LogOperMember log=new LogOperMember();
					log.setType(10);				//操作类别(10系统登录)
					log.setMemberId(member.getId());
					log.setTitle("系统登录");
					
					String operIp=request.getRemoteHost();
					log.setOperIp(operIp);
					
					log.setCommitDate(new Date());
					log.setContext("登录失败");
					logOperMemberService.saveOrUpdate(log); 
		        	
					setMessage(model,"用户名或密码不正确!");
					
				}
					
				return "login";
				
			}
		}else{
			setMessage(model,"用户不存在!");
			return "login";
		}
		
	}

	private Member verifyUser(String loginName) throws Exception{
		//String pwd = member.getOnePassword();
		// 前台超级用户
		
		Member member = memberService.executMemberByLoginName(loginName);
		
		return member;
	}

	

	/***
	 * 前台退出
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("memberLogoff.shtml")
	public String logoff(HttpServletRequest request) throws Exception{
		removeSession(request.getSession());
		return "login";
	}

	private void removeSession(HttpSession session) {
		Enumeration sessionNames = session.getAttributeNames();
		String sessionName = "";
		while (sessionNames.hasMoreElements()) {
			sessionName = sessionNames.nextElement().toString();
			session.removeAttribute(sessionName);
		}
		session.invalidate();
	}


}
